import { BadRequestException, Controller, Post, UploadedFile } from '@nestjs/common'
import { CdncordService } from '@boticord/cdncord'
import { Action, fromJwt, fromResponse, PermissionsTo, UserToken } from '@boticord/auth'
import { ApiFile, getFileBlobMimeType } from '../api-file.decorator'
import { ErrorCodes, Limits, SupportedMimeTypes } from '@boticord/consts'
import { AnalyseRequest, EventTypes } from '@boticord/analytics'

@Controller('upload')
export class CdnController {
  constructor(private readonly cdn: CdncordService) {}

  @Post()
  @PermissionsTo(Action.Premium, UserToken)
  @ApiFile('file', {
    limits: { fileSize: Limits.MaxCdnFileSize },
  })
  @AnalyseRequest(EventTypes.FileUploaded, {
    user: fromJwt('id'),
    extract: fromResponse('url'),
  })
  public upload(
    @UploadedFile() file: Express.Multer.File,
  ) {
    const mime = getFileBlobMimeType(file.buffer)
    if (!SupportedMimeTypes.some((m) => m === mime))
      throw new BadRequestException({ code: ErrorCodes.UnsupportedMediaType })
    return this.cdn.upload(file.buffer, getFileBlobMimeType(file.buffer))
  }
}